{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 方法一：用字典计数, 时间O(n) ， 空间O(n)\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def deleteDuplicates(self, head: ListNode) -> ListNode:\n",
    "        s = {}\n",
    "        H = ListNode(0)\n",
    "        H.next = head\n",
    "        p = head\n",
    "        while(p):\n",
    "            if(p.val in s):\n",
    "                s[p.val] += 1\n",
    "            else:\n",
    "                s[p.val] = 1\n",
    "            p = p.next\n",
    "        p = head\n",
    "        q = H\n",
    "        while(p):\n",
    "            temp = p.next\n",
    "            if(s[p.val] > 1):\n",
    "                q.next = p.next\n",
    "                del p\n",
    "                p = temp\n",
    "            else:\n",
    "                p = temp\n",
    "                q = q.next\n",
    "        return H.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 方法二：时间O(n), 空间O(1)\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def deleteDuplicates(self, head: ListNode) -> ListNode:\n",
    "        if(head == None or head.next == None):\n",
    "            return head\n",
    "        H = ListNode(None) # 添加首节点\n",
    "        H.next = head\n",
    "        tail = H\n",
    "        prev = head\n",
    "        curr = head.next\n",
    "        curr_equal = False\n",
    "        prev_equal = False\n",
    "        # tail->prev->curr, 若prev值等于curr值，或上一次相等，则删除prev指向的节点。\n",
    "        while(curr):\n",
    "            curr_equal = (curr.val == prev.val)\n",
    "            if(curr_equal or prev_equal):\n",
    "                tail.next = curr\n",
    "                #del prev\n",
    "            else:\n",
    "                tail = prev\n",
    "            prev = curr\n",
    "            curr = curr.next\n",
    "            prev_equal = curr_equal\n",
    "        if(curr_equal):\n",
    "            tail.next = None\n",
    "        return H.next"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
